package cn.tedu.charging.order.config;


import org.springframework.amqp.core.*;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.HashMap;
import java.util.Map;


@Configuration
public class RabbitMqConfig {
    public static final String EXCHANGE_NAME = "charging_order_exchange";
    public static final String QUEUE_NAME = "charging_order_queue";
    public static final String ROUTING_KEY = "charging_order_routing_key";


    private static final String DEAD_LETTER_EXCHANGE_NAME = "dead_letter_charging_order_exchange";
    public static final String DEAD_LETTER_QUEUE_NAME = "dead_letter_charging_order_queue";
    private static final String DEAD_LETTER_ROUTING_NAME = "dead_letter_routing_key";

    @Bean
    public DirectExchange orderExchange(){
        return new DirectExchange(EXCHANGE_NAME,true,false);
    }

    @Bean
    public Queue orderQueue(){
        Boolean durable = true;
        Map<String,Object> arg = new HashMap<>();

        Integer ttl = 60 * 1000;
        arg.put("x-message-ttl",ttl);
        arg.put("x-dead-letter-exchange",DEAD_LETTER_EXCHANGE_NAME);
        //设置queue和死信Exchange 绑定 routing_key
        arg.put("x-dead-letter-routing-key",DEAD_LETTER_ROUTING_NAME);
        //惰性队列,在消息很多的时候,把消息存储到磁盘,避免消息积压,占用内存
        arg.put("x-queue-mode","lazy");

        return new Queue(QUEUE_NAME,durable,true,false,arg);
    }

    @Bean
    public Binding orderBinding(){
        return BindingBuilder
                .bind(orderQueue())
                .to(orderExchange())
                .with(ROUTING_KEY);
    }

    // 死信队列
    @Bean
    public DirectExchange deadLetterOrderExchange(){
        return new DirectExchange(DEAD_LETTER_EXCHANGE_NAME,true,false);
    }

    @Bean
    public Queue deadLetterOrderQueue(){
        return new Queue(DEAD_LETTER_QUEUE_NAME,true);
    }

    @Bean
    public Binding deadLetterOrderBinding(){
        return BindingBuilder
                .bind(deadLetterOrderQueue())
                .to(deadLetterOrderExchange())
                .with(DEAD_LETTER_ROUTING_NAME);
    }
}
